package com.fc.advbox.common.upload;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.fileupload.FileUploadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class QiniuFileUploadManager implements FileUploadManager {

    private static final Logger log = LoggerFactory.getLogger(QiniuFileUploadManager.class);

    private Auth auth;
    private String bucket;
    private String imgHost;
    private UploadManager uploadManager;

    public QiniuFileUploadManager(String accessKey, String secretKey, String bucket, String imgHost) {
        this.auth = Auth.create(accessKey, secretKey);
        this.bucket = bucket;
        this.imgHost = imgHost;
        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);
        this.uploadManager = new UploadManager(c);
    }

    @Override
    public String upload(MultipartFile file) throws FileUploadException {
        try {
            if (!file.isEmpty()) {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
                //调用put方法上传
                Response res = uploadManager.put(file.getBytes(), filename, getUpToken());
                //打印返回的信息
                log.debug(res.bodyString());
                return imgHost + "/" + filename;
            } else {
                throw new FileUploadException("File is empty");
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            log.error(r.toString());
            throw new FileUploadException("Failed to upload file to qiniu, QiniuException occur", e);
        } catch (IOException e) {
            throw new FileUploadException("Failed to upload file to qiniu, IOException occur", e);
        }
    }

    @Override
    public String[] batchUpload(List<MultipartFile> files) throws FileUploadException {
        String[] paths = new String[files.size()];
        int i = 0;
        for (MultipartFile file : files) {
            paths[i++] = upload(file);
        }
        return paths;
    }

    public String getUpToken() {
        return auth.uploadToken(bucket);
    }

}
